package cn.signalpha.modules.shop.controller.admin;

import cn.signalpha.common.annotation.OperateLogAnnotation;
import cn.signalpha.common.constant.AppConstant;
import cn.signalpha.common.constant.MsgConstant;
import cn.signalpha.common.dto.AuditDTO;
import cn.signalpha.common.utils.Assert;
import cn.signalpha.core.boot.ctrl.BaseController;
import cn.signalpha.core.log.exception.ServiceException;
import cn.signalpha.core.mp.support.Condition;
import cn.signalpha.core.mp.support.Query;
import cn.signalpha.core.tool.api.R;
import cn.signalpha.core.tool.jackson.JsonUtil;
import cn.signalpha.core.tool.support.Kv;
import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.modules.shop.dto.GoodsDTO;
import cn.signalpha.modules.shop.entity.Goods;
import cn.signalpha.modules.shop.entity.GoodsSnapshot;
import cn.signalpha.modules.shop.entity.enums.GoodsStatusEnum;
import cn.signalpha.modules.shop.service.*;
import cn.signalpha.modules.shop.vo.GoodsVO;
import cn.signalpha.modules.shop.wrapper.GoodsWrapper;
import cn.signalpha.modules.system.entity.enums.OperateLogTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器
 *
 * @author signalpha
 */
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_SHOP_NAME + "/admin/goods")
@Api(value = "商品", tags = "商品")
public class GoodsController extends BaseController {

	private final CartService cartService;
    private final GoodsService goodsService;
	private final GoodsSkuService goodsSkuService;
	private final GoodsSpecService goodsSpecService;
	private final GoodsAttrService goodsAttrService;
	private final PatternGoodsService patternGoodsService;
	private final GoodsSnapshotService goodsSnapshotService;
	private final PublicityGoodsService publicityGoodsService;

    @GetMapping("/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name="name", dataType = "string", value = "名称"),
		@ApiImplicitParam(name="type", dataType = "string", value = "类型"),
		@ApiImplicitParam(name="status", dataType = "string", value = "状态"),
		@ApiImplicitParam(name="sellerId", dataType = "string", value = "商户id"),
		@ApiImplicitParam(name="categoryId", dataType = "string", value = "分类id"),
		@ApiImplicitParam(name="isHot", dataType = "string", value = "是否热门"),
		@ApiImplicitParam(name="isPush", dataType = "string", value = "是否推荐"),
	})
	@ApiOperationSupport(order = 1)
    @ApiOperation(value = "分页", notes = "")
    public R<IPage<GoodsVO>> page(@ApiIgnore @RequestParam Map<String, Object> params, Query query) {
		QueryWrapper<Goods> wrapper = goodsService.selectGoodsWrapper(params);
		IPage<Goods> page = goodsService.page(Condition.getPage(query), wrapper);
		return R.data(GoodsWrapper.build().pageVO(page));
    }

	@GetMapping("/status")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "状态统计", notes = "")
	public R<Map<String, Object>> status(@ApiIgnore @RequestParam Map<String, Object> params) {
		Map<String, Object> map = new HashMap<>();
		map.put("data", goodsService.countByParams(Kv.create()));
		map.put("data0", goodsService.countByParams(Kv.create().setAll(params).set("status", "0")));
		map.put("data1", goodsService.countByParams(Kv.create().setAll(params).set("status", "1")));
		map.put("data-1", goodsService.countByParams(Kv.create().setAll(params).set("status", "-1")));
		map.put("data-2", goodsService.countByParams(Kv.create().setAll(params).set("status", "-2")));
		map.put("data-3", goodsService.countByParams(Kv.create().setAll(params).set("status", "-3")));
		return R.data(map);
	}

	@GetMapping("/info")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "详情", notes = "传入id")
	public R<GoodsVO> info(@RequestParam Long id) {
		return R.data(GoodsWrapper.build().entityVO(goodsService.getById(id)));
	}

	@PostMapping("/save")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "保存", notes = "")
	@OperateLogAnnotation(remark = "新增 - 商品", operateType = OperateLogTypeEnum.SAVE)
	public R save(@RequestBody Goods goodsDTO) {
		Long goodsId = goodsService.saveGoods(goodsDTO);
		GoodsVO goodsVO = GoodsWrapper.build().entityVO(goodsService.getById(goodsId));
		goodsSnapshotService.saveGoodsSnapshot(goodsVO, getUser().getUserId(), 30);
		return R.status(true);
	}

	@PostMapping("/save/batch")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "批量保存", notes = "")
	public R saveBatch(@RequestBody List<Goods> goodsList) {
		goodsList.forEach(goodsDTO -> {
			Long goodsId = goodsService.saveGoods(goodsDTO);
			GoodsVO goodsVO = GoodsWrapper.build().entityVO(goodsService.getById(goodsId));
			goodsSnapshotService.saveGoodsSnapshot(goodsVO, getUser().getUserId(), 30);
		});
		return R.status(true);
	}

	@PostMapping("/update")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "修改", notes = "")
	@OperateLogAnnotation(remark = "修改 - 商品", operateType = OperateLogTypeEnum.UPDATE)
	public R update(@RequestBody Goods goodsDTO) {
		goodsDTO.setUpdateTime(new Date());
		Long goodsId = goodsService.updateGoods(goodsDTO);
		GoodsVO goodsVO = GoodsWrapper.build().entityVO(goodsService.getById(goodsId));
		goodsSnapshotService.saveGoodsSnapshot(goodsVO, getUser().getUserId(), 31);
		cartService.removeByGoodsId(goodsDTO.getId().toString());
		return R.status(true);
	}

	@PostMapping("/audit")
	@ApiOperationSupport(order = 15)
	@ApiOperation(value = "审核", notes = "")
	@OperateLogAnnotation(remark = "审核 - 商品", operateType = OperateLogTypeEnum.AUDIT)
	public R audit(@Valid @RequestBody AuditDTO auditDTO) {
		Func.toLongList(auditDTO.getIds()).forEach(id -> {
			Goods goods = goodsService.getById(id);
			Assert.isNull(goods, MsgConstant.OBJECT_NULL);
			if(goods.getStatus().equals(GoodsStatusEnum.DOWN_HEAD.getType())){
				throw new ServiceException("当前状态不可审核");
			}
			if(auditDTO.getStatus() == 1){
				goodsService.updateById(Goods.builder().id(goods.getId()).status(GoodsStatusEnum.DOWN.getType()).remark(auditDTO.getRemark()).build());
			}else {
				goodsService.updateById(Goods.builder().id(goods.getId()).status(GoodsStatusEnum.REJECT.getType()).remark(auditDTO.getRemark()).build());
			}
		});
		return R.status(true);
	}

    @PostMapping("/up")
	@ApiOperationSupport(order = 12)
    @ApiOperation(value = "上架", notes = "传入ids")
	@OperateLogAnnotation(remark = "上架 - 商品", operateType = OperateLogTypeEnum.UPDATE)
	public R up(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(goodsService.update(Wrappers.<Goods>lambdaUpdate().set(Goods::getStatus, 1).in(Goods::getId, Func.toLongList(ids))));
    }

    @PostMapping("/down")
	@ApiOperationSupport(order = 13)
    @ApiOperation(value = "下架", notes = "传入ids")
	@OperateLogAnnotation(remark = "下架 - 商品", operateType = OperateLogTypeEnum.UPDATE)
	public R down(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(goodsService.update(Wrappers.<Goods>lambdaUpdate().set(Goods::getStatus, 0).in(Goods::getId, Func.toLongList(ids))));
    }

	@PostMapping("/down/force")
	@ApiOperationSupport(order = 14)
	@ApiOperation(value = "强制下架", notes = "传入ids")
	@OperateLogAnnotation(remark = "强制下架 - 商品", operateType = OperateLogTypeEnum.UPDATE)
	public R downForce(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(goodsService.update(Wrappers.<Goods>lambdaUpdate().set(Goods::getStatus, -1).in(Goods::getId, Func.toLongList(ids))));
	}

	@PostMapping("/update/category/batch")
	@ApiOperationSupport(order = 15)
	@ApiOperation(value = "批量修改商品分类", notes = "")
	public R saveBatch(@RequestBody GoodsDTO.@Valid UpdateCategoryDTO goodsDTO) {
		return R.status(goodsService.update(Wrappers.<Goods>lambdaUpdate().set(Goods::getCategoryId, goodsDTO.getCategoryId()).in(Goods::getId, Func.toLongList(goodsDTO.getIds()))));
	}

	@PostMapping("/update/salesVolumeVirtual/batch")
	@ApiOperationSupport(order = 15)
	@ApiOperation(value = "批量修改虚拟销量", notes = "")
	public R saveSalesVolumeVirtualBatch(@RequestBody GoodsDTO.@Valid UpdateSalesVolumeVirtualDTO goodsDTO) {
		return R.status(goodsService.update(Wrappers.<Goods>lambdaUpdate().set(Goods::getSalesVolumeVirtual, goodsDTO.getSalesVolumeVirtual()).in(Goods::getId, Func.toLongList(goodsDTO.getIds()))));
	}

	@PostMapping("/remove")
	@ApiOperationSupport(order = 20)
	@ApiOperation(value = "删除", notes = "传入ids")
	@OperateLogAnnotation(remark = "删除 - 商品", operateType = OperateLogTypeEnum.DELETE)
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		goodsService.listByIds(Func.toLongList(ids)).forEach(goods -> {
			goodsService.removeById(goods.getId());
			cartService.removeByGoodsId(goods.getId());
			goodsSkuService.removeByGoodsId(goods.getId());
			goodsAttrService.removeByGoodsId(goods.getId());
			goodsSpecService.removeByGoodsId(goods.getId());
			goodsSnapshotService.removeByGoodsId(goods.getId());
			publicityGoodsService.removeByGoodsId(goods.getId());
			patternGoodsService.removeByGoodsId(goods.getId());
		});
		return R.status(true);
	}

	@GetMapping("/snapshot/page")
	@ApiOperationSupport(order = 50)
	@ApiOperation(value = "快照分页", notes = "")
	public R<IPage<GoodsSnapshot>> snapshotPage(@ApiIgnore @RequestParam Map<String, Object> params, Query query) {
		QueryWrapper<GoodsSnapshot> queryWrapper = Condition.getQueryWrapper(params, GoodsSnapshot.class);
		return R.data(goodsSnapshotService.page(Condition.getPage(query), queryWrapper.lambda().orderByDesc(GoodsSnapshot::getId)));
	}

	@GetMapping("/snapshot/info")
	@ApiOperationSupport(order = 51)
	@ApiOperation(value = "快照详情", notes = "传入id")
	public R<GoodsVO> snapshotInfo(@RequestParam Long id) {
		GoodsSnapshot goodsSnapshot = goodsSnapshotService.getById(id);
		return R.data(JsonUtil.parse(goodsSnapshot.getDetail(), GoodsVO.class));
	}

}
